<?php
/**
 * Created by PhpStorm.
 * User: Da Xiong
 * Date: 2019/1/28
 * Time: 16:59
 */

namespace App\HttpController\Admin;


use App\Model\CatesModel;

class CategoryController extends AuthController
{
    /**
     * 获取 分类管理_列表
     */
    public function index(){
        $request = $this->request();
        $name = $request->getRequestParam('name')??'';
        $page = (int)$request->getRequestParam('page')??0;
        if($page < 1){
            $page = 1;
        }
        $catesModel = new CatesModel();
        if($name){
            $catesModel->where('name','%'.$name.'%','like');
        }
        $catesModel->orderBy('id','DESC');
        $lists = $catesModel->paginate($page);
        return $this->writeJson(0, $lists);
    }

    /**
     * 分类管理_新增
     */
    public function update(){
        $request = $this->request();
        $params = $request->getRequestParam();
        $catesModel = new CatesModel();
        if(isset($params['id']) && (int)$params['id'] > 0){
            //修改
            $cateInfo = $catesModel->find($params['id']);
            if(!$cateInfo){
                return $this->writeJson(1, null,'数据不存在');
            }
            $isUpdate = $catesModel->update($params);
            if($isUpdate){
                return $this->writeJson(0, null,'编辑成功');
            }
            return $this->writeJson(1, null,'系统错误');
        }
        //新增
        if(isset($params['id'])){
            unset($params['id']);
        }
        $isSave = $catesModel->create($params);
        if($isSave){
            return $this->writeJson(0, null,'新增成功');
        }
        return $this->writeJson(1, null,'系统错误');
    }

    /**
     * 分类管理_删除
     */
    public function destroy()
    {
        $request = $this->request();
        $id = (int)$request->getRequestParam('id')??0;
        if($id === 0){
            return $this->writeJson(1, null,'参数错误');
        }
        $videoModel = new CatesModel();
        $isDelete = $videoModel->destroy($id);
        if(!$isDelete){
            return $this->writeJson(1, null,'删除失败');
        }
        return $this->writeJson(0, null,'删除成功');
    }

}
